package com.luxiu;

import javafx.application.Platform;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
import javafx.stage.Stage;
import javafx.stage.Window;
import javafx.stage.WindowEvent;

import java.io.*;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;


/**
 * JavaFX App
 */
public class App extends FrameLess {

    public static boolean isFading = false;
    private final String fileLockId = "kkndmKsfhe6fUXmpGQ7Rt6mL3L4jX-8e";
    private String fileLockPath = "";
    private FileChannel fileLockChannel;
    private FileOutputStream fileLockOutputStream;
    private FileLock fileLock; // 单例文件锁

    public final double minWidth = 700;
    public final double minHeight = 420;

    /**
     * 淡入窗口
     *
     * @param primaryStage Stage
     */
    public static void fadeInWindow(Stage primaryStage) {
        new Thread(() -> {
            isFading = true;
            float opacity = 0;
            while (opacity <= 1) {
                float finalOpacity = opacity;
                Platform.runLater(() -> primaryStage.setOpacity(finalOpacity));
                opacity += 0.03;
                try {
                    Thread.sleep(50);
                } catch (InterruptedException ignored) {
                }
            }
            isFading = false;
        }).start();
    }

    @Override
    public void init() {
        setSingleton();
        super.init();
    }

    @Override
    public void start(Stage stage) throws Exception {
        LoadingStartPage loadingStartPage = new LoadingStartPage();
        loadingStartPage.start(new Stage());

        super.start(stage);
        stage.setWidth(1000);
        stage.setHeight(600);
        new Thread(() -> {
            try {
                // 3s后显示主程序
                Thread.sleep(3000);
                // 只能在JavaFx线程中改变，为阻塞方法
                Platform.runLater(() -> {
                    loadingStartPage.exit();
                    stage.setOpacity(0);
                    stage.show();
                    fadeInWindow(stage);
                });
            } catch (InterruptedException e) {
                System.err.println(e.getMessage());
            }
        }).start();

        // 退出程序删除文件锁文件
        closeControl.addEventHandler(MouseEvent.MOUSE_CLICKED, event -> {
            if (event.getButton() == MouseButton.PRIMARY) {
                exit();
            }
        });
        // 窗口关闭 hook
        stage.addEventHandler(WindowEvent.WINDOW_CLOSE_REQUEST, event -> {
            exit();
        });
    }

    /**
     * 退出程序
     */
    private void exit() {
        new File(fileLockPath).deleteOnExit();
        clickCloseControl();
        try {
            fileLock.release();
            if (fileLockChannel.isOpen()) {
                fileLockChannel.close();
            }
            fileLockOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void setSingleton() {
        boolean error = false;
        File file = new File(new File("").getAbsolutePath(), fileLockId);
        fileLockPath = file.getAbsolutePath();
        // 文件不存在则创建文件
        if (!file.exists()) {
            try {
                if (!file.createNewFile()) {
                    error = true;
                }
            } catch (IOException e) {
                e.printStackTrace();
                error = true;
            }
        }

        if (error) {
            // 创建文件失败
            System.exit(-1);
        }

        try {
            fileLockOutputStream = new FileOutputStream(file);
            fileLockChannel = fileLockOutputStream.getChannel();
            fileLock = fileLockChannel.tryLock();
            // 获取锁失败
            if (fileLock == null) {
                error = true;
                // 获取主屏幕焦点
                Window.getWindows().get(0).requestFocus();
            }
        } catch (IOException e) {
            e.printStackTrace();
            error = true;
        }

        if (error) {
            // 获取锁失败退出程序
            System.exit(-1);
        }
    }

    public static void main(String[] args) {
        launch();
    }

}